package tcpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * 简单的TCP服务器测试类
 * 
 * 不依赖Spring Boot，纯Netty实现，用于测试基本功能
 */
public class SimpleTcpServerTest {
    
    private static final int PORT = 8080;
    
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new SimpleServerHandler());
                        }
                    });
            
            // 绑定端口并启动服务器
            ChannelFuture future = bootstrap.bind(PORT).sync();
            System.out.println("=================================");
            System.out.println("   简单TCP服务器启动成功！");
            System.out.println("   端口: " + PORT);
            System.out.println("   使用telnet测试: telnet localhost " + PORT);
            System.out.println("=================================");
            
            // 等待服务器关闭
            future.channel().closeFuture().sync();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
    
    /**
     * 简单的消息处理器
     */
    static class SimpleServerHandler extends ChannelInboundHandlerAdapter {
        
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            System.out.println("客户端连接: " + ctx.channel().remoteAddress());
            
            // 发送欢迎消息
            String welcome = "欢迎连接到RTU TCP服务器！\n发送 'PING' 测试心跳\n发送 'QUIT' 断开连接\n";
            ctx.writeAndFlush(Unpooled.copiedBuffer(welcome, CharsetUtil.UTF_8));
        }
        
        @Override
        public void channelInactive(ChannelHandlerContext ctx) {
            System.out.println("客户端断开: " + ctx.channel().remoteAddress());
        }
        
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf byteBuf = (ByteBuf) msg;
            
            try {
                String receivedMessage = byteBuf.toString(CharsetUtil.UTF_8).trim();
                System.out.println("收到消息: " + receivedMessage);
                
                String response = processMessage(receivedMessage, ctx);
                if (response != null) {
                    ctx.writeAndFlush(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));
                }
                
            } finally {
                byteBuf.release();
            }
        }
        
        private String processMessage(String message, ChannelHandlerContext ctx) {
            if (message.isEmpty()) {
                return null;
            }
            
            // 心跳测试
            if ("PING".equalsIgnoreCase(message)) {
                return "PONG\\n";
            }
            
            // 断开连接
            if ("QUIT".equalsIgnoreCase(message)) {
                ctx.writeAndFlush(Unpooled.copiedBuffer("再见！\\n", CharsetUtil.UTF_8))
                   .addListener(ChannelFutureListener.CLOSE);
                return null;
            }
            
            // 检查SL651报文
            if (message.matches("^[0-9A-Fa-f]+$") && message.length() >= 40) {
                return "检测到SL651协议报文，长度: " + message.length() + " 字符\\n";
            }
            
            // 默认回显
            return "回显: " + message + "\\n";
        }
        
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            System.err.println("连接异常: " + cause.getMessage());
            ctx.close();
        }
    }
}